package org.wtframework.platform.server.util;

import java.io.File;
import java.util.Date;
import java.util.List;

import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.openredhead.springx.core.server.service.FilePaths;

/**
 * 
 * <B>类描述：</B> （导出表格） <br/><br/>
 * <B>作者：</B> 黄杰帆 <br/><br/>
 * <B>创建日期：</B> 2013-6-8 下午5:29:07 
 *
 */
public class ExportExcelUtil {
	
	public static String exportExcel(String title, List<String> nameStr, List<List<String>> userList) {

		String url = "";

		try {
			
			String name = "/files/temporary/table/" + new Date().getTime() + ".xls";
			url = name.replace(FilePaths.getSystemRootPath(), "");
			int rowId = 0;
			String file = "/files/temporary/table";
			File dFile = new File(FilePaths.getSystemRootPath()+ file);
			if(!dFile.exists()){
				dFile.mkdirs();
			}

			WritableWorkbook wbook = jxl.Workbook.createWorkbook(new File(FilePaths.getSystemRootPath() + name));
			WritableSheet wsheet = null;
			WritableFont titleFont =  new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD);
			WritableCellFormat titleFormat = new WritableCellFormat( titleFont);
			
			if(title == null || "".equals(title)) {
				
				wsheet = wbook.createSheet("wbook", 0);
			} else {
				
				rowId = 1;
				wsheet = wbook.createSheet(title, 0);
				
				WritableFont wfont = new WritableFont(WritableFont.createFont("宋体"), 18, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE);
				WritableCellFormat wcfFC = new WritableCellFormat(wfont);
				wcfFC.setBackground(Colour.AQUA);  //单元格背景
				wcfFC.setAlignment(Alignment.CENTRE);  //单元格左右居中
				wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE); //单元格中的内容垂直方向居中
				wsheet.addCell(new Label(0, 0, title, wcfFC));
				wsheet.mergeCells(0, 0, nameStr.size()-1, 0);
			}

			//初始化列头
			for (int i = 0; i < nameStr.size(); i++) {
				WritableCellFormat tempTitleFormat = new WritableCellFormat(titleFont);
				tempTitleFormat.setBackground(Colour.GRAY_25);
				wsheet.addCell(new Label(i, rowId, nameStr.get(i),tempTitleFormat));
				wsheet.setColumnView(i,30); //设置excel的每一列的宽度
				wsheet.setRowView(i,500); //单元格行高
			}

			for (int i = 0; i < userList.size(); i++) {
				
				List<String> strList = userList.get(i);
				for (int j = 0; j < strList.size(); j++) {
					String str = strList.get(j);
					wsheet.addCell(new Label(j, rowId + 1 + i, str,titleFormat));
					wsheet.setRowView(rowId + 1 + i,500); //单元格行高
				}
			}
			wsheet.setRowView(0,1000); //单元格行高
			wbook.write();
			wbook.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		url.replace("\\", "/");

		return url;
	}

}
